/**
 * 列表转成树
 * @param {*} list list
 * @param {*} id node-key
 * @param {*} pid parent key
 * @param {*} childrenKey children key
 */
export const listToTree = (list, id = 'id', pkey = 'pid', childrenKey = 'children') => {
    const map = new Map()
    const newList = []
    list && list.forEach(item => {
        map.set(item[id], item)
    })
    map.forEach((item) => {
        if (map.has(item[pkey])) {
            const parent = map.get(item[pkey])
            parent[childrenKey] = parent[childrenKey] || []
            parent[childrenKey].push(item)
        } else {
            newList.push(item)
        }
    })
    return newList
}

/**
 * 树转列表
 * @param {*} tree 树数组
 * @param {*} list 接收结果的数据
 * @param {*} childrenKey 子项的key
 */
export const treeToList = (tree = [], list = [], childrenKey = 'children', handleMethod) => {
    tree.forEach(node => {
        if (typeof handleMethod === 'function') {
            handleMethod(node)
        }
        list.push(node)
        if (node[childrenKey] && node[childrenKey].length) {
            treeToList(node[childrenKey], list, childrenKey, handleMethod)
        }
    })
}

/**
 * 树组件过滤，返回新的数组
 * @param {*} tree 数据列表
 * @param {*} propKey 子项的要过滤的字段名
 * @param {*} value 要过滤的值
 * @param {*} matchPid 匹配的父级ID列表
 * @param {*} idKey id名称
 * @param {*} pid pid
 * @param {*} parentFilterKey 父级元素的字段名
 */
export const filterTree = (tree, propKey, value, childrenKey = 'children', idKey = 'id', pid = 'pid', parentFilterKey = propKey, matchPid = []) => {
    const filterList = []
    tree.forEach(item => {
        const newItem = { ...item }
        const pIncludes = item[parentFilterKey] && item[parentFilterKey].includes(value)
        if (pIncludes) {
            matchPid.push(item[idKey])
            filterList.push(newItem)
        } else if (item[childrenKey] && item[childrenKey].length) {
            if (pIncludes) {
                matchPid.push(item[idKey])
            }
            newItem[childrenKey] = filterTree(item[childrenKey], propKey, value, childrenKey, idKey, pid, parentFilterKey, matchPid)
            if (newItem[childrenKey].length || pIncludes) {
                filterList.push(newItem)
            }
        } else if (matchPid.includes(item[pid])) {
            filterList.push(item)
        } else if (Array.isArray(propKey)) {
            propKey.forEach(pItem => {
                if (item[pItem] && item[pItem].includes(value)) {
                    filterList.push(item)
                }
            })
        } else if (item[propKey] && item[propKey].includes(value)) {
            filterList.push(item)
        }
    })
    return filterList
}

